<%@ page import="com.googlecode.jwsm.*" %>

var mainClassWindow;
var uploadState = 'mainClass';
var customInstantiationRequired = false;

function validateJARs() {
	var i = 0;
	var jars = '';
	while (document.getElementById('jarSpan' + i) != null) {
		if (document.getElementById('fileName' + i) != null) {
			jars = jars + '|' + document.getElementById('jar' + i).value + ':' + document.getElementById('fileName' + i).value;
		}
		i++;
	}
	if (jars == '') {
		alert('Please specify at least one JAR first.');
	}
	return jars;
}

function chooseMainClass() {
	if (mainClassWindow != null) {
		mainClassWindow.close();
	}
	
	var jars = validateJARs();
	if (jars.length > 0) {
		mainClassWindow = window.open('choose_main.jsp?jars=' + jars, 'chooseMainClass', 'width=400,height=400,scrollbars=yes,resizable=1');
	}
	return false;
}

function dependencyDuplicationCheck() {
	if (mainClassWindow != null) {
		mainClassWindow.close();
	}
	
	var jars = validateJARs();
	if (jars.length > 0) {
		mainClassWindow = window.open('dependency_duplication.jsp?jars=' + jars, 'dependencyDuplicationCheck', 'width=500,height=400,scrollbars=yes,resizable=1');
	}
}

function setMainClass(mainClass) {
	document.getElementById('mainClass').value = mainClass;
}

function validateSubmit() {
	var name = document.getElementById('name').value;
	if (name == '') {
		alert('Service name cannot be empty');
		return;
	} else if (name.indexOf('/') != -1) {
		alert('Invalid character \'/\' in service name');
		return;
	} else if (name.indexOf('\\') != -1) {
		alert('Invalid character \'\\\' in service name');
		return;
	} else if (name.indexOf('!') != -1) {
		alert('Invalid character \'!\' in service name');
		return;
	} else if (name.indexOf('?') != -1) {
		alert('Invalid character \'?\' in service name');
		return;
	} else if (name.indexOf('|') != -1) {
		alert('Invalid character \'|\' in service name');
		return;
	}
	if (document.getElementById('mainClass').value == '') {
		alert('Main Class must be specified');
		return;
	}
	
	// Validate if custom instantiation is required
	if (customInstantiationRequired) {
		if (document.getElementById('instantiation').value == '') {
			if (!confirm('It is recommended that a custom instantiation be specified.\n\nAre you sure you wish to proceed without specifying this?')) {
				return;
			}
		}
	}
	
	uploadState = 'submit';
	validateUploads();
}

function submitService() {
	if (validateJARs() == '') {
		return;
	}

	document.getElementById('serviceForm').action = 'Deploy';
	document.getElementById('serviceForm').target = '_top';
	document.getElementById('serviceForm').encoding = 'application/x-www-form-urlencoded';
	document.getElementById('serviceForm').submit();
}

function executeAction(name, optionList) {
	var option = optionList.options[optionList.selectedIndex].value;
	
	// Eval Execute Action
	if (name == 'Eval') {
		eval(option);
	}
	
	// Service Execute Actions
	if (option == 'Start') {
		document.location = 'index.jsp?service=' + name + '&action=start';
	} else if (option == 'Stop') {
		document.location = 'index.jsp?service=' + name + '&action=stop';
	} else if (option == 'Restart') {
		document.location = 'index.jsp?service=' + name + '&action=restart';
	} else if (option == 'Test') {
		document.location = 'test.jsp?service=' + name;
	} else if (option == 'Configure') {
		document.location = 'service.jsp?service=' + name;
	} else if (option == 'Undeploy') {
		if (confirm('Are you sure you wish to undeploy the service: "' + name + '"?\n\nThis cannot be undone.')) {
			document.location = 'index.jsp?service=' + name + '&action=undeploy';
		}
	} else if (option == 'Generate Client') {
		document.location = 'generate_client.jsp?service=' + name;
	}
	
	// WSAR Execute Actions
	if (option == 'Download') {
		document.location = 'WebServiceArchive?action=download&value=' + name;
	} else if (option == 'Deploy') {
		document.location = 'WebServiceArchive?action=deploy&value=' + name;
	} else if (option == 'Delete') {
		if (confirm('Are you sure you want to delete this WSAR?')) {
			document.location = 'WebServiceArchive?action=delete&value=' + name;
		}
	}
	optionList.selectedIndex = 0;
}

function clearMethods() {
	var v = document.getElementById('defaultMethod');
	v.length = 0;
	v.options[v.length] = new Option('<no default method>', '', false);
	document.getElementById('availableMethods').innerHTML = '';
}

function addMethod(methodName, outgoingXSLT, incomingXSLT) {
	var v = document.getElementById('defaultMethod');
	v.options[v.length] = new Option(methodName, methodName, false);
			
	var v = document.getElementById('availableMethods');
	var checkbox = document.createElement('input');
	checkbox.setAttribute('type', 'checkbox');
	checkbox.setAttribute('name', 'visibleMethod');
	checkbox.setAttribute('id', methodName);
	checkbox.setAttribute('value', methodName);
	v.appendChild(checkbox);
	checkbox.checked = true;
	v.appendChild(document.createTextNode(methodName));
	
	var d = document.createElement('div');
	d.style.fontSize = '12px';
	d.setAttribute('width', '100%');
	d.setAttribute('align', 'right');
	
	// Incoming XSLT
	if (incomingXSLT != null) {
		var b = document.createElement('b');
		b.appendChild(document.createTextNode('Incoming: '));
		d.appendChild(b);
		var optionList = document.createElement('select');
		optionList.setAttribute('name', methodName + 'IncomingXSLT');
		optionList[0] = new Option('<none>', '<none>', false);
		optionList[1] = new Option('<default>', '<default>', true);
		<%
		{
			XSLT[] xslts = ServiceManager.getInstance().getIncomingXSLTs();
			for (int i = 0; i < xslts.length; i++) {
		%>
			optionList[<%= i + 2 %>] = new Option('<%= xslts[i].getName() %>', '<%= xslts[i].getName() %>', false);
		<%
			}
		}
		%>
		if (incomingXSLT == 'null') {
			incomingXSLT = '<default>';
		}
		for (var i = 0; i < optionList.length; i++) {
			if (optionList.options[i].value == incomingXSLT) {
				optionList.selectedIndex = i;
				break;
			}
		}
		d.appendChild(optionList);
	}
	
	// Outgoing XSLT
	if (outgoingXSLT != null) {
		b = document.createElement('b');
		b.appendChild(document.createTextNode(' Outgoing: '));
		d.appendChild(b);
		optionList = document.createElement('select');
		optionList.setAttribute('name', methodName + 'OutgoingXSLT');
		optionList[0] = new Option('<none>', '<none>', false);
		optionList[1] = new Option('<default>', '<default>', true);
		<%
		{
			XSLT[] xslts = ServiceManager.getInstance().getOutgoingXSLTs();
			for (int i = 0; i < xslts.length; i++) {
		%>
			optionList[<%= i + 2 %>] = new Option('<%= xslts[i].getName() %>', '<%= xslts[i].getName() %>', false);
		<%
			}
		}
		%>
		if (outgoingXSLT == 'null') {
			outgoingXSLT = '<default>';
		}
		for (var i = 0; i < optionList.length; i++) {
			if (optionList.options[i].value == outgoingXSLT) {
				optionList.selectedIndex = i;
				break;
			}
		}
		d.appendChild(optionList);
	}
	
	v.appendChild(d);
}

function changeXSLTType() {
	var v = document.getElementById('defaultClass');
	v.length = 0;
	v.options[v.length] = new Option('<no default association>', '', false);
	if (document.getElementById('xsltType')[document.getElementById('xsltType').selectedIndex].value == 'outgoing') {
		<%
			String[] types = ServiceManager.getInstance().getServiceReturnTypes();
			for (int i = 0; i < types.length; i++) {
		%>
				v[<%= i + 1 %>] = new Option('<%= types[i] %>', '<%= types[i] %>', false);
		<%
			}
		%>
	} else {
		<%
			types = ServiceManager.getInstance().getServiceParameterTypes();
			for (int i = 0; i < types.length; i++) {
		%>
				v[<%= i + 1 %>] = new Option('<%= types[i] %>', '<%= types[i] %>', false);
		<%
			}
		%>
	}
}

function expand(formNumber, paramNumber) {
	var text = document.getElementById('param' + formNumber + ':' + paramNumber).value;
	document.getElementById('span' + formNumber + ':' + paramNumber).innerHTML = '<textarea cols="50" rows="8" id="param' + formNumber + ':' + paramNumber + '" name="param' + paramNumber + '"></textarea>';
	document.getElementById('param' + formNumber + ':' + paramNumber).value = text;
}

function contract(spanId, inputId) {
	var span = document.getElementById(spanId);
	var text = document.getElementById(inputId).value;
	span.innerHTML = '<input type="text" id="' + inputId + '" name="' + inputId + '" value="' + document.getElementById(inputId).value + '"/> ' +
					 '<input type="button" value="Expand" onclick="expand(\'' + spanId + '\', \'' + inputId + '\');"/>';
	document.getElementById(inputId).value = text;
}

function changeJar() {
	var jars = new Array();

	var id = 0;
	var emptyExists = false;
	while (document.getElementById('jarSpan' + id) != null) {
		if (document.getElementById('jar' + id) != null) {
			if (document.getElementById('jar' + id).value == '') {
				emptyExists = true;
			} else {
				for (var i = 0; i < jars.length; i++) {
					if (document.getElementById('jar' + id).value == jars[i]) {
						alert('JAR already added: ' + jars[i]);
						document.getElementById('jarSpan' + id).innerHTML = '<input type="file" id="jar' + id + '" name="jar' + id + '" onchange="changeJar();"/><input type="button" value="Remove" id="RemoveJAR" onclick="removeJar(' + id + ');"/><br/>'
						return;
					}
				}
				jars[jars.length] = document.getElementById('jar' + id).value;
			}
		}
		id++;
	}
	if (!emptyExists) {
		if (document.getElementById('jarSpan' + id) == null) {
			var jarSpan = document.createElement('span');
			jarSpan.setAttribute('id', 'jarSpan' + id);
			jarSpan.innerHTML = '<input type="file" id="jar' + id + '" name="jar' + id + '" onchange="changeJar();"/><input type="button" value="Remove" id="RemoveJAR" onclick="removeJar(' + id + ');"/><br/>'
			document.getElementById('jars').appendChild(jarSpan);
		} else {
			document.getElementById('jarSpan' + id).innerHTML = '<input type="file" id="jar' + id + '" name="jar' + id + '" onchange="changeJar();"/><input type="button" value="Remove" id="RemoveJAR" onclick="removeJar(' + id + ');"/><br/>'
		}
	}
	//alert(document.getElementById('jarTD').innerHTML);
}

function removeJar(id) {
	document.getElementById('jarSpan' + id).innerHTML = '';
	changeJar();
}

var uploadWindow;
function validateUploads() {
	// Determine if there are any files to be uploaded
	var fileToUpload = false;
	var i = 0;
	while (document.getElementById('jarSpan' + i) != null) {
		if ((document.getElementById('jar' + i) != null) && (document.getElementById('jar' + i).getAttribute('type') == 'file')) {
			if (document.getElementById('jar' + i).value != '') {
				fileToUpload = true;
			}
		}
		i++;
	}
	if (fileToUpload) {
		uploadWindow = window.open('upload_window.jsp', 'uploadWindow', 'width=400,height=200');
		document.getElementById('serviceForm').submit();
	} else {
		if (uploadState == 'mainClass') {
			chooseMainClass();
		} else if (uploadState == 'dependencyDuplication') {
			dependencyDuplicationCheck();
		} else {
			submitService();
		}
	}
	
	return false;
}

function updateUploads() {
	ajaxRequest(location.href.substring(0, location.href.lastIndexOf('/') + 1) + 'Uploader?request=progress', null);
}

function updateProgress(progress) {
	if (uploadWindow != null) {
		if (progress < 1) {
			uploadWindow.document.getElementById('uploadSpan').innerHTML = '<table width="250" cellpadding="0" cellspacing="0" class="table"><tr><td width="' + (100 - progress) + '" bgcolor="#ffffff">&#160;</td></tr></table>';
		} else if (progress == 100) {
			uploadWindow.document.getElementById('uploadSpan').innerHTML = '<table width="250" cellpadding="0" cellspacing="0" class="table"><tr><td width="' + progress + '" bgcolor="<%= CSSDefaults.BG_COLOR %>">&#160;</td></tr></table>';
			if (uploadState == 'mainClass') {
				setTimeout('uploadWindow.close(); chooseMainClass();', 500);
			} else if (uploadState == 'dependencyDuplication') {
				setTimeout('uploadWindow.close(); dependencyDuplicationCheck();', 500);
			} else {
				setTimeout('uploadWindow.close(); submitService();', 500);
			}
		} else {
			uploadWindow.document.getElementById('uploadSpan').innerHTML = '<table width="250" cellpadding="0" cellspacing="0" class="table"><tr><td width="' + progress + '" bgcolor="<%= CSSDefaults.BG_COLOR %>">&#160;</td><td width="' + (100 - progress) + '" bgcolor="#ffffff">&#160;</td></tr></table>';
		}
		uploadWindow.document.getElementById('uploadPercent').innerHTML = progress + '%';
	}
}

function updateUploadText(text) {
	if (uploadWindow != null) {
		uploadWindow.document.getElementById('uploadText').innerHTML = text;
	}
}

function finishedUpload(id, localName, remoteName) {
	var span = document.getElementById('jarSpan' + id);
	span.innerHTML = '<input type="text" name="jar' + id + '" id="jar' + id + '" readonly="readonly"/><input type="hidden" name="fileName' + id + '" id="fileName' + id + '"/><input type="button" value="Remove" onclick="removeJar(' + id + ');"/><br/>';
	document.getElementById('jar' + id).value = localName;
	document.getElementById('fileName' + id).value = remoteName;
}

function trim(str) {
	str = this != window? this : str;
	return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function populateTestParameters(methodNumber, parameterCount) {
	for (var i = 0; i < parameterCount; i++) {
		expand(methodNumber, i);
		document.getElementById('param' + methodNumber + ':' + i).value = document.getElementById('testParam' + methodNumber + ':' + i).value;
	}
}

function setEnabled(id, enabled) {
	document.getElementById(id).disabled = !enabled;
}

function requireCustomInstantiation(customInstantiationRequired) {
	this.customInstantiationRequired = customInstantiationRequired;
}